<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="130px"
      status-icon
    >
      <el-form-item label="食物名称" prop="foodName">
        <el-input
          v-model="ruleForm.foodName"
          placeholder="请输入食物名称"
          min="0"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item label="蛋白质(g)" prop="protein">
        <el-input
          v-model="ruleForm.protein"
          placeholder="请输入蛋白质"
          type="number"
          min="0"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item label="脂肪(g)" prop="fat">
        <el-input
          v-model="ruleForm.fat"
          placeholder="请输入脂肪"
          type="number"
          min="0"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item label="碳水(g)" prop="carbohydrate">
        <el-input
          v-model="ruleForm.carbohydrate"
          placeholder="请输入碳水"
          type="number"
          min="0"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item label="热量(千卡)" prop="caloric">
        <el-input
          v-model="ruleForm.caloric"
          placeholder="请输入热量"
          type="number"
          min="0"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item label="不溶性膳食纤维(g)" prop="fiber">
        <el-input v-model="ruleForm.fiber" type="number" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="胆固醇(mg)" prop="cholesterol">
        <el-input
          v-model="ruleForm.cholesterol"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="维生素A(ugRAE)" prop="vitamina">
        <el-input
          v-model="ruleForm.vitamina"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="维生素C(mg)" prop="vitaminc">
        <el-input
          v-model="ruleForm.vitaminc"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="钙(mg)" prop="calcium">
        <el-input
          v-model="ruleForm.calcium"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="钾(mg)" prop="potassium">
        <el-input
          v-model="ruleForm.potassium"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="钠(mg)" prop="sodium">
        <el-input v-model="ruleForm.sodium" type="number" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="血糖生成指数" prop="givalue">
        <el-input
          v-model="ruleForm.givalue"
          type="number"
          min="0"
          size="mini"
        />
      </el-form-item>
      <el-form-item label="食物分类" prop="type">
        <el-select
          v-model="ruleForm.type"
          placeholder="食物分类"
          class="handle-select mr10"
        >
          <span>
            <el-option key="0" label="暂无" value="0"></el-option>
          </span>
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in categoryList"
            :key="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="食物状态" prop="unit">
        <el-radio-group v-model="ruleForm.unit">
          <el-radio :label="0" value="0">固体</el-radio>
          <el-radio :label="1" value="1">液体</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="食物描述" prop="desc">
        <el-input
          v-model="ruleForm.desc"
          placeholder="请输入食物描述"
          type="textarea"
          rows="6"
        ></el-input>
      </el-form-item>
      <el-form-item label="选择图片" height="40">
        <el-upload
          action="#"
          :multiple="false"
          accept=".jpg,.jpeg,.png"
          :show-file-list="true"
          list-type="picture-card"
          @change="handelFileChange"
          :auto-upload="false"
        >
          <el-image class="avatar" v-if="imageUrl" :src="imageUrl">
            <template #placeholder>
              <div class="image-slot">Loading<span class="dot">...</span></div>
            </template>
          </el-image>
          <el-icon v-else>
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">jpg/png格式图片且图片大小不能超过500kb</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <span class="dialog-footer">
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >更新</el-button
      >
      <el-button @click="resetForm">重置表单</el-button>
      <el-button @click="handleReturn">取消</el-button>
    </span>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { es } from 'element-plus/es/locale'
export default {
  components: {},
  setup() {
    const router = useRouter()

    const route = useRoute()
    const checkValidator = (rule, value, callback) => {
      if (value > 5000) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    const rules = reactive({
      foodName: [
        {
          required: true,
          message: '请输入食物名称',
          trigger: 'blur',
        },
      ],
      protein: [
        {
          required: true,
          message: '请输入蛋白质',
          trigger: 'blur',
        },
        {
          validator: checkValidator,
          message: '请输入正确的蛋白质含量(0~100)',
        },
      ],
      fat: [
        {
          required: true,
          message: '请输入脂肪',
          trigger: 'blur',
        },
        {
          validator: checkValidator,
          message: '请输入正确的脂肪含量(0~100)',
        },
      ],
      carbohydrate: [
        {
          required: true,
          message: '请输入碳水',
          trigger: 'blur',
        },
        {
          validator: checkValidator,
          message: '请输入正确的碳水含量(0~100)',
        },
      ],
      caloric: [
        {
          required: true,
          message: '请输入热量',
          trigger: 'blur',
        },
        {
          validator: checkValidator,
          message: '请输入正确的热量(0~5000)',
        },
      ],
      type: [
        {
          required: true,
          message: '请选择食物类型',
          trigger: 'change',
        },
      ],
    })
    const categoryList = [
      { id: 0, name: '其他' },
      { id: 1, name: '谷类及制品' },
      { id: 2, name: '薯类、淀粉及制品' },
      { id: 3, name: '干豆类及制品' },
      { id: 4, name: '蔬菜类及制品' },
      { id: 5, name: '菌藻类' },
      { id: 6, name: '水果类及制品' },
      { id: 7, name: '坚果、种子类' },
      { id: 8, name: '植物油' },
      { id: 9, name: '畜肉类及制品' },
      { id: 10, name: '禽肉类及制品' },
      { id: 11, name: '乳类及制品' },
      { id: 12, name: '蛋类及制品' },
      { id: 13, name: '鱼虾蟹贝类' },
      { id: 14, name: '油脂' },
      { id: 15, name: '婴幼儿食品' },
      { id: 16, name: '小吃、甜饼' },
      { id: 17, name: '速食食品' },
      { id: 18, name: '饮料类' },
      { id: 19, name: '含酒精饮料' },
      { id: 20, name: '糖、果脯和蜜饯、蜂蜜类' },
      { id: 21, name: '调味品类' },
    ]
    const ruleFormRef = ref({})
    const ruleForm = ref({
      foodId: route.query.foodId,
      foodName: '',
      type: 3,
      unit: 0,
    })
    const imageUrl = ref('')
    const foods = JSON.parse(sessionStorage.getItem(ruleForm.value.foodId))
    if (route.query.foodId) {
      ruleForm.value.foodId = foods.foodId
      ruleForm.value.foodName = foods.foodName
      ruleForm.value.type = foods.type
      ruleForm.value.protein = foods.protein
      ruleForm.value.fat = foods.fat
      ruleForm.value.carbohydrate = foods.carbohydrate
      ruleForm.value.caloric = foods.caloric
      ruleForm.value.fiber = foods.fiber
      ruleForm.value.cholesterol = foods.cholesterol
      ruleForm.value.vitamina = foods.vitamina
      ruleForm.value.vitaminc = foods.vitaminc
      ruleForm.value.calcium = foods.calcium
      ruleForm.value.potassium = foods.potassium
      ruleForm.value.sodium = foods.sodium
      ruleForm.value.givalue = foods.givalue
      ruleForm.value.avator = foods.avator
      imageUrl.value = foods.avator
      ruleForm.value.desc = foods.desc
    } else {
      router.push('/foodTable')
    }

    const selectedFile = ref(null)

    // 重置表单
    const resetForm = (formEl) => {
      ruleForm.value.foodId = foods.foodId
      ruleForm.value.foodName = foods.foodName
      ruleForm.value.protein = foods.protein
      ruleForm.value.fat = foods.fat
      ruleForm.value.carbohydrate = foods.carbohydrate
      ruleForm.value.caloric = foods.caloric
      ruleForm.value.fiber = foods.fiber
      ruleForm.value.cholesterol = foods.cholesterol
      ruleForm.value.vitamina = foods.vitamina
      ruleForm.value.vitaminc = foods.vitaminc
      ruleForm.value.calcium = foods.calcium
      ruleForm.value.potassium = foods.potassium
      ruleForm.value.sodium = foods.sodium
      ruleForm.value.givalue = foods.givalue
      ruleForm.value.avator = foods.avator
      imageUrl.value = foods.avator
      ruleForm.value.desc = foods.desc
      ElNotification({
        title: '重置成功',
        message: '重置成功',
      })
    }

    // 获取文件数据

    const handelFileChange = (file) => {
      const isLt500k = file.raw.size / 1024 < 500
      if (!isLt500k) {
        ElNotification({
          title: '图片过大',
          message: '图片不能超过500k',
        })
        return
      }
      selectedFile.value = file.raw
      imageUrl.value = URL.createObjectURL(file.raw)
    }
    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      formData.append('foodId', ruleForm.value.foodId)
      formData.append('foodName', ruleForm.value.foodName)
      formData.append('protein', Number(ruleForm.value.protein))
      formData.append('fat', Number(ruleForm.value.fat))
      formData.append('carbohydrate', Number(ruleForm.value.carbohydrate))
      formData.append('caloric', Number(ruleForm.value.caloric))
      formData.append('type', ruleForm.value.type)
      formData.append('unit', ruleForm.value.unit)
      formData.append('fiber', Number(ruleForm.value.fiber))
      formData.append('cholesterol', Number(ruleForm.value.cholesterol))
      formData.append('vitamina', Number(ruleForm.value.vitamina))
      formData.append('vitaminc', Number(ruleForm.value.vitaminc))
      formData.append('calcium', Number(ruleForm.value.calcium))
      formData.append('potassium', Number(ruleForm.value.potassium))
      formData.append('sodium', Number(ruleForm.value.sodium))
      if (ruleForm.value.givalue === '') {
        ruleForm.value.givalue = null
      }
      formData.append('givalue', ruleForm.value.givalue)
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      }
      if (ruleForm.value.desc) {
        formData.append('desc', ruleForm.value.desc)
      }

      return formData
    }

    const formData = ref(null)
    // 提交表单
    const submitForm = async (ruleFormRef) => {
      formData.value = processFormData()
      if (!ruleFormRef) return
      await ruleFormRef.validate((valid, fields) => {
        console.log(typeof ruleForm.value.givalue)
        if (valid) {
          request
            .request({
              url: '/food/updateFood',
              method: 'post',
              data: formData.value,
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '更新成功',
                  message: '成功更新食物信息',
                })
                router.push('/foodTable')
              } else {
                ElNotification({
                  title: '更新失败1',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              // console.log(e)
              ElNotification({
                title: '更新失败',
                message: '请联系管理员检查失败原因',
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }

    const handleReturn = () => {
      router.push('/foodTable')
    }
    return {
      ruleForm,
      ruleFormRef,
      rules,
      handelFileChange,
      submitForm,
      resetForm,
      imageUrl,
      categoryList,
      handleReturn,
    }
  },
}
</script>

<style lang="scss" scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.dot {
  animation: dot 2s infinite steps(3, start);
  overflow: hidden;
}
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}

.avatar{
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
